﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Dal.Models;
using Framework.Common;
using Framework.Common.Extention;
using Framework.Common.LinqExtention;
using NPOI.SS.UserModel;

namespace Web.Controllers
{
    [MyAuthAttribute(Role = 0)]
    [ValidateInput(false)]
    public class TongxunController : Controller
    {
        #region search
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Manage()
        {
            CHACTOR query = new CHACTOR();
            TryUpdateModel(query);
            int pageindex = TypeConvertHelper.StrToInt(Request["pageindex"], 1);
            ViewBag.Record = QueryCHACTOR(query);
            return View(query);
        }
        /// <summary>
        /// export
        /// </summary>
        /// <returns></returns>
        public ActionResult Export()
        {
            CHACTOR query = new CHACTOR();
            TryUpdateModel(query);
            var list = QueryCHACTOR(query);
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            NPOI.SS.UserModel.IWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook();
            var sheet = book.CreateSheet("export");
            var rowTitle = sheet.CreateRow(0);
            var cellTitle0 = rowTitle.CreateCell(0);
            var cellTitle1 = rowTitle.CreateCell(1);
            var cellTitle2 = rowTitle.CreateCell(2);
            var cellTitle3 = rowTitle.CreateCell(3);
            var cellTitle4 = rowTitle.CreateCell(4);

            cellTitle0.SetCellValue("姓名");
            cellTitle1.SetCellValue("电话");
            cellTitle2.SetCellValue("电子邮件");
            cellTitle3.SetCellValue("地址");
            cellTitle4.SetCellValue("分组");


            int index = 1;
            foreach (var model in list)
            {
                var row = sheet.CreateRow(index);
                var cell0 = row.CreateCell(0);
                var cell1 = row.CreateCell(1);
                var cell2 = row.CreateCell(2);
                var cell3 = row.CreateCell(3);
                var cell4 = row.CreateCell(4);


                cell0.SetCellValue(model.NAME);
                cell1.SetCellValue(model.PHONE);
                cell2.SetCellValue(model.EMAIL);
                cell3.SetCellValue(model.ADDRESS);
                cell4.SetCellValue(model.TEAM);


                index++;
            }
            var bytes = new byte[] { };
            using (var ms = new MemoryStream())
            {
                book.Write(ms);
                bytes = ms.ToArray();
            }

            return File(bytes, contentType, "通讯录导出.xlsx");
        }
        /// <summary>
        /// search chactor
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private IList<CHACTOR> QueryCHACTOR(CHACTOR query)
        {
            using (MessageContext db = new MessageContext())
            {
                IQueryable<CHACTOR> list = db.CHACTORs;
                string owner = Common.GetUserName();
                Expression<Func<CHACTOR, bool>> exp = m => m.OWNER == owner;
                if (!string.IsNullOrWhiteSpace(query.ADDRESS))
                {
                    exp = exp.And(i => i.ADDRESS.Contains(query.ADDRESS));
                }
                if (!string.IsNullOrWhiteSpace(query.EMAIL))
                {
                    exp = exp.And(i => i.EMAIL.Contains(query.EMAIL));
                }
                if (!string.IsNullOrWhiteSpace(query.NAME))
                {
                    exp = exp.And(i => i.NAME.Contains(query.NAME));
                }
                if (!string.IsNullOrWhiteSpace(query.PHONE))
                {
                    exp = exp.And(i => i.PHONE == query.PHONE);
                }
                if (!string.IsNullOrWhiteSpace(query.TEAM))
                {
                    exp = exp.And(i => i.TEAM == query.TEAM);
                }
                return list.Where(exp).ToList();
            }
        }
        #endregion

        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }
        /// <summary>
        /// add chactor
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Add(FormCollection form)
        {
            CHACTOR model = new CHACTOR();
            TryUpdateModel(model);
            model.OWNER = Common.GetUserName();
            ViewBag.Result = InsertCHACTOR(model);
            return View();
        }

        /// <summary>
        /// batch import
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BatchAdd(FormCollection form)
        {
            NPOI.SS.UserModel.IWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook(Request.Files[0].InputStream);
            var sheet = book.GetSheetAt(0);
            sheet.GetRow(0);
            for (int i = 1; i < sheet.LastRowNum; i++)
            {
                CHACTOR model = new CHACTOR();
                model.OWNER = Common.GetUserName();
                var row = sheet.GetRow(i);
                ICell cell0 = row.GetCell(0);
                if (cell0 != null)
                {
                    model.NAME = cell0.ToString();
                }
                else
                {
                    model.NAME = "";
                }
                ICell cell1 = row.GetCell(1);
                if (cell1 != null)
                {
                    model.PHONE = cell1.ToString();
                }
                else
                {
                    model.PHONE = "";
                }
                ICell cell2 = row.GetCell(2);
                if (cell2 != null)
                {
                    model.EMAIL = cell2.ToString();
                }
                else
                {
                    model.EMAIL = "";
                }
                ICell cell3 = row.GetCell(3);
                if (cell3 != null)
                {
                    model.ADDRESS = cell3.ToString();
                }
                else
                {
                    model.ADDRESS = "";
                }
                ICell cell4 = row.GetCell(4);
                if (cell4 != null)
                {
                    model.TEAM = cell4.ToString();
                }
                else
                {
                    model.TEAM = "";
                }
                InsertCHACTOR(model);
            }

            ViewBag.Result = true;
            Response.Write("<script>alert('导入成功');window.location.href='/tongxun/add';</script>");
            return null;
        }

        private bool InsertCHACTOR(CHACTOR model)
        {
            using (MessageContext db = new MessageContext())
            {
                var tmp = db.CHACTORs.Where(i => i.PHONE == model.PHONE && i.OWNER == model.OWNER).FirstOrDefault();
                if (tmp == null)
                {
                    db.CHACTORs.Add(model);
                    return db.SaveChanges() > 0;
                }
                else
                {
                    db.CHACTORs.Attach(tmp);
                    tmp.ADDRESS = model.ADDRESS;
                    tmp.EMAIL = model.EMAIL;
                    tmp.NAME = model.NAME;
                    tmp.TEAM = model.TEAM;
                    return db.SaveChanges() > 0;
                }
            }
        }

        /// <summary>
        /// delete chactor
        /// </summary>
        /// <returns></returns>
        public ActionResult Delete()
        {
            var id = RequestExtention.GetInt(
                System.Web.HttpContext.Current.Request
                , "id");
            bool success = false;
            using (MessageContext db = new MessageContext())
            {
                success = db.Database.ExecuteSqlCommand("delete from CHACTOR where id = {0} and owner = {1}", id, Common.GetUserName()) > 0;
            }
            return Json(new { result = success }, JsonRequestBehavior.AllowGet);
        }
    }
}
